<?php
// app/controller/Crawler.php
namespace app\controller\wow;

use think\facade\Db;
use think\facade\Log;
use app\model\wow\WupinModel;
use think\facade\Cache;
use think\facade\Request;
class Crawler
{
    // const TARGET_URL = 'https://7881.com/wow-classic/gold/hardcore-anniversary/';
    // const TARGET_URL = 'https://search.7881.com/G5569-100001-G5569P002-G5569P002002-0.html?pageNum=1';
    const TARGET_URL = 'https://db.nfuwow.com/60/?items';
    const WOW_URL = 'https://db.nfuwow.com/60/?item';  // 魔兽物品 抓取地址

    public function fetchGoldPrices()
    {
        try {
            // 抓取联盟数据
            // $allianceData = $this->crawlPage('alliance');
            $allianceData = $this->crawlPage('');
            $this->saveData($allianceData);

            // 抓取部落数据
            // $tribeData = $this->crawlPage('tribe');
            $tribeData = $this->crawlPage('');
            $this->saveData($tribeData);

            return '抓取完成';
        } catch (\Exception $e) {
            Log::error("抓取失败: {$e->getMessage()}");
            return '抓取异常，请查看日志';
        }
    }

    private function crawlPage(string $faction)
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => self::TARGET_URL . $faction,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer: https://7881.com/'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false
        ]);

        $html = curl_exec($ch);
        if (curl_errno($ch)) throw new \Exception(curl_error($ch));
        curl_close($ch);

        return $this->parseHtml($html, $faction);
    }

    private function parseHtml(string $html, string $faction = '')
    {
        $dom = new \DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new \DOMXPath($dom);

        // 示例解析逻辑（需根据实际页面结构调整）
        $nodes = $xpath->query("//div[contains(@class,'price-list')]/div[@class='item']");
        
        $data = [];
        foreach ($nodes as $node) {
            $priceNode = $xpath->query(".//span[@class='gold-price']", $node)->item(0);
            if ($priceNode) {
                $data[] = [
                    'server' => '硬汉服务器',
                    'faction' => $faction,
                    'price' => (float)preg_replace('/[^0-9.]/', '', $priceNode->nodeValue),
                    'create_time' => date('Y-m-d H:i:s')
                ];
            }
        }
        return $data;
    }

    private function saveData(array $data)
    {
        
        if (!empty($data)) {
            Db::name('wow_gold_price')->insertAll($data);
        }
    }


    private function getInnerHTML( \DOMNode $node): string {
        $innerHTML = '';
        foreach ($node->childNodes as $child) {
            $innerHTML .= $node->ownerDocument->saveHTML($child);
        }
        return $innerHTML;
    }

    // 获取魔兽物品列表
    // 访问链接：https://tp.x-mii.com/wow.Crawler/getItems
    public function getItems(){

        //todo 获取 redis 中缓存的页码
        $redis = Cache::store('redis')->handler();
        $current_page = $redis->Get('wow::zhuaqu::page');
        if( empty( $current_page ) ){
            $current_page = 1;
        }

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => self::WOW_URL . "s&page=" . $current_page,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer: https://db.nfuwow.com/60/'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false
        ]);

        $html = curl_exec($ch);
        if (curl_errno($ch)) throw new \Exception(curl_error($ch));
        curl_close($ch);

        
        // 使用 DOM 解析器加载 HTML 响应
        libxml_use_internal_errors(true); // 禁用 libxml 错误报告
        $dom = new \DOMDocument();
        @$dom->loadHTML($html); // 使用 @ 符号抑制可能的 HTML 解析警告
        libxml_clear_errors(); // 清除 libxml 错误堆栈

        // 获取所有 table 元素
        $tables = $dom->getElementsByTagName('tbody');

        // 假设我们需要第一个 table 元素中的数据
        if ($tables->length > 0) {
            $table = $tables->item(0);

            // 获取 table 中的所有行
            $rows = $table->getElementsByTagName('tr');
            
            $data = [];
            foreach ($rows as $row) {
                // 获取行中的所有单元格
                $cells = $row->getElementsByTagName('td');
                $rowData = [];

                


                
                foreach ($cells as $key => $cell) {
                    if( $key  == 0 ) {
                        $ins = $cell->getElementsByTagName('ins')[0];
                        $styleContent = $ins->getAttribute('style');
                        $styleContent = ltrim( $styleContent, "background-image: url('");
                        $styleContent = rtrim( $styleContent, ")';");
                        $rowData['image'] = $styleContent;

                        $a = $cell->getElementsByTagName('a')[0];
                        $hrefContent = $a->getAttribute('href');
                        $hrefContent = ltrim( $hrefContent, "?item=");
                        $rowData['item_id'] = $hrefContent;
                    }else if( $key ==  1){
                        // $allName = trim($cell->textContent);
                        // $allName = trim($cell->innerHTML);
                        $allName = $this->getInnerHTML( $cell->getElementsByTagName('a')[0] );
                        list($name, $ename ) = explode('<br>', $allName );
                        $rowData['name'] = $name;
                        $rowData['ename'] = $ename;

                    }else if( $key == 2 ){
                        $a = $cell->getElementsByTagName('a')[0];
                        $hrefContent = $a->getAttribute('href');
                        $hrefContent = ltrim( $hrefContent, "?items&quality=");
                        $rowData['quality_no'] = trim($hrefContent);
                        
                        $rowData['quality'] = trim($cell->textContent);
                    }else if( $key == 3 ){
                        // 提取单元格中的文本内容
                        $rowData['level'] = trim($cell->textContent);
                    }else if( $key == 4 ){
                        // 提取单元格中的文本内容
                        $rowData['reqlevel'] = trim($cell->textContent);
                    }else if( $key == 5 ){
                        // 提取单元格中的文本内容
                        $rowData['type'] = trim($cell->textContent);
                    }

                }
                $data[] = $rowData;

            }
            
            // 插入数据库
            // $wupin = WupinModel::insert( $rowData );
            $wupinModel = new WupinModel();
            $result = $wupinModel->saveAll( $data );
            $current_page += 1;
            $redis->Set('wow::zhuaqu::page', $current_page );
            // 返回解析后的数据
            return json($result);
        } else {
            return json(['error' => 'No table found in the page'], 404);
        }


    }

    // 获取魔兽物品详情
    // 访问链接：https://tp.x-mii.com/wow.Crawler/getItem
    public function getItem(){
        
        $_GPC = Request::param(  );
        $item_id = $_GPC['item_id'];

        $html = WupinModel::zhuaquDetail( $item_id );

        // $ch = curl_init();
        // curl_setopt_array($ch, [
        //     CURLOPT_URL => self::WOW_URL . "=" . $item_id,
        //     CURLOPT_RETURNTRANSFER => true,
        //     CURLOPT_HTTPHEADER => [
        //         'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        //         'Referer: https://db.nfuwow.com/60/'
        //     ],
        //     CURLOPT_TIMEOUT => 15,
        //     CURLOPT_SSL_VERIFYPEER => false
        // ]);

        // $html = curl_exec($ch);
        // if (curl_errno($ch)) throw new \Exception(curl_error($ch));
        // curl_close($ch);

        
        // // 使用 DOM 解析器加载 HTML 响应
        // libxml_use_internal_errors(true); // 禁用 libxml 错误报告
        // $dom = new \DOMDocument();
        // @$dom->loadHTML($html); // 使用 @ 符号抑制可能的 HTML 解析警告
        // libxml_clear_errors(); // 清除 libxml 错误堆栈

        // // 获取所有 table 元素
        // $tables = $dom->getElementsByTagName('table');


        // $html = $tables[2]->C14N();
        // // echo htmlspecialchars($html);

        echo $html;

    }
}
